export const registerAccount = async (
    client, username, password, session,
) => new Promise((resolve, reject) => {
    client.register(username, password, session, null, null, null, null, (err, result) => {
        // console.log(err, "\n", result);
        if (err && err.httpStatus !== 401) {
            reject(err);
            return;
        }
        if (!err) {
            resolve(result);
            return;
        }
        const sessionID = err.data.session;
        client.register(username, password, sessionID, {
            type: err.data.flows[0].stages[0],
        }, null, null, null, (newErr, newResult) => {
            if (newErr) reject(newErr);
            resolve(newResult);
        });
    });
});

export const deactivateAccount = async (client, username, password) => {
    let result;
    try {
        await client.deactivateAccount(null, true);
    } catch (err) {
        if (err.httpStatus !== 401) return Promise.reject(err);
        try {
            result = await client.deactivateAccount({
                type: err.data.flows[0].stages[0],
                session: err.data.session,
                user: username,
                password,
            }, true);
        } catch (newErr) {
            return Promise.reject(newErr);
        }
    }
    return result;
};

export const loginAccount = (client, username, password) => new Promise((resolve, reject) => {
    client.login("m.login.password", {
        user: username,
        password,
    }, (err, result) => {
        if (err) reject(err);
        resolve(result);
    });
});
